/* eslint-disable no-unused-vars */
const noop = () => {};
let _currentEffect = null;

function useObserve(obj) {
  const _observers = new Set();
  const observable = (obj) => new Proxy(obj, handler);
  const observe = (fn) => _observers.add(fn);
  const disObserve = (fn) => _observers.delete(fn);

  const handler = {
    set(...args) {
      const success = Reflect.set(...args);
      if (success) {
        _observers.forEach((fn) => fn(...args));
      }
      return success;
    },
    get(...args) {
      _currentEffect && observe(_currentEffect);
      return Reflect.get(...args);
    },
  };

  return {
    observed: observable(obj),
    createEffect: (fn) => {
      _currentEffect = fn;
      fn?.();
      _currentEffect = null;
    },
    removeObserver: disObserve,
  };
}

const { observed: Me, createEffect } = useObserve({
  name: "zpj",
  age: 27,
  address: "China",
});

const printWhenChange = () => console.log("CHANGED");
createEffect(printWhenChange);

Me.address = "America";
